from flask import request, jsonify
from ..models.event import Event
from ..extensions import db
from ..utils.response import pagination, error, success
from datetime import datetime

# 创建活动
def create_event(data):
    
    # 检查必填字段
    required_fields = ['name', 'start_time', 'end_time', 'registration_start_time', 'registration_end_time']
    for field in required_fields:
        if field not in data:
            return error(f"{field} is required", 400)
    
    # 处理时间字段
    try:
        start_time = datetime.strptime(data['start_time'], '%Y-%m-%d %H:%M:%S')
        end_time = datetime.strptime(data['end_time'], '%Y-%m-%d %H:%M:%S')
        registration_start_time = datetime.strptime(data['registration_start_time'], '%Y-%m-%d %H:%M:%S')
        registration_end_time = datetime.strptime(data['registration_end_time'], '%Y-%m-%d %H:%M:%S')
    except ValueError:
        return error("Invalid datetime format, should be YYYY-MM-DD HH:MM:SS", 400)
    
    # 验证时间逻辑
    if start_time >= end_time:
        return error("Start time must be before end time", 400)
    
    if registration_start_time >= registration_end_time:
        return error("Registration start time must be before registration end time", 400)
    
    if registration_end_time >= end_time:
        return error("Registration end time must be before event end time", 400)
    
    # 创建活动
    event = Event(
        name=data['name'],
        start_time=start_time,
        end_time=end_time,
        registration_start_time=registration_start_time,
        registration_end_time=registration_end_time,
        url=data.get('url'),
        address=data.get('address'),
        description=data.get('description')
    )
    
    db.session.add(event)
    db.session.commit()
    
    return success("Event created successfully", event.to_dict())

# 获取活动列表
def get_events(data):
    """获取活动列表，支持分页"""
    try:
        query = Event.query
        
        # 计算总数
        total = query.count()
        
        # 按开始时间倒序排列
        query = query.order_by(Event.start_time.desc())
        
        # 获取分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 处理无效的分页参数
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100  # 限制最大每页记录数
        
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 获取分页数据
        events = query.offset(offset).limit(page_size).all()
        
        # 返回分页数据
        return pagination(
            items=[event.to_dict() for event in events],
            total=total,
            msg='获取成功',
            code=200
        )
    except Exception as e:
        return error('获取失败', 500)

# 获取单个活动信息
def get_event(data):
    # 从请求参数中获取活动ID
    event_id = data.get('id')
    
    if not event_id:
        return error("Event ID is required", 400)
    
    try:
        event_id = int(event_id)
    except ValueError:
        return error("Invalid event ID", 400)
    
    event = Event.query.get(event_id)
    if not event:
        return error("Event not found", 404)
    
    return success(event.to_dict(),"Event found")

# 更新活动信息
def update_event(data):
    
    # 从请求数据中获取活动ID
    event_id = data.get('id')
    
    if not event_id:
        return error("Event ID is required", 400)
    
    try:
        event_id = int(event_id)
    except ValueError:
        return error("Invalid event ID", 400)
    
    event = Event.query.get(event_id)
    if not event:
        return error("Event not found", 404)
    
    # 更新活动信息
    if 'name' in data:
        event.name = data['name']
    
    # 处理时间字段更新
    time_fields = ['start_time', 'end_time', 'registration_start_time', 'registration_end_time']
    for field in time_fields:
        if field in data:
            try:
                setattr(event, field, datetime.strptime(data[field], '%Y-%m-%d %H:%M:%S'))
            except ValueError:
                return error(f"Invalid {field} format, should be YYYY-MM-DD HH:MM:SS", 400)
    
    # 重新验证时间逻辑
    if event.start_time >= event.end_time:
        return error("Start time must be before end time", 400)
    
    if event.registration_start_time >= event.registration_end_time:
        return error("Registration start time must be before registration end time", 400)               
    
    if event.registration_end_time >= event.end_time:
        return error("Registration end time must be before event end time", 400)
    
    # 更新其他字段
    if 'address' in data:
        event.address = data['address']
    
    if 'description' in data:
        event.description = data['description']
    
    db.session.commit()
    
    return success("Event updated successfully", event.to_dict())

# 删除活动
def delete_event():
    data = request.get_json()
    
    # 从请求数据中获取活动ID
    event_id = data.get('id')
    
    if not event_id:
        return error("Event ID is required", 400)
    
    try:
        event_id = int(event_id)
    except ValueError:
        return error("Invalid event ID", 400)
    
    event = Event.query.get(event_id)
    if not event:
        return error("Event not found", 404)
    
    db.session.delete(event)
    db.session.commit()
    
    return success("Event deleted successfully")
